<template>
  <div>
    <a-spin :tip="loadTips" :spinning="spinning" size="large">
      <div
        style="
          display: flex;
          align-items: center;
          justify-content: center;
          align-content: center;
          margin-bottom: 21px;
        "
      >
        <div style="font-size: 28px; text-align: center">用户登录</div>
      </div>
      <a-tabs v-model:activeKey="activeKey">
        <a-tab-pane key="tab1" tab="账号密码登录">
          <a-form layout="horizontal" :rules="pwdRules" :model="formPwd" @finish="handleSubmit">
            <a-form-item required hasFeedback name="username">
              <a-input v-model:value="formPwd.username" size="large" placeholder="请输入用户名">
                <template #prefix
                  ><user-outlined type="user" :style="{ color: 'rgba(0,0,0,.25)' }"
                /></template>
              </a-input>
            </a-form-item>
            <a-form-item required hasFeedback name="password">
              <a-input
                v-model:value="formPwd.password"
                size="large"
                type="password"
                placeholder="请输入密码"
              >
                <template #prefix
                  ><lock-outlined type="user" :style="{ color: 'rgba(0,0,0,.25)' }"
                /></template>
              </a-input>
            </a-form-item>
            <div id="captcha" style="width: 450px; max-height: 40px; margin-bottom: 22px"></div>
            <a-form-item>
              <a-button type="primary" html-type="submit" size="large" :loading="loading" block>
                登录
              </a-button>
            </a-form-item>
          </a-form>
        </a-tab-pane>
        <a-tab-pane key="tab2" tab="手机号登录" :force-render="true">
          <a-form
            layout="horizontal"
            :rules="mobileRules"
            :model="formMobile"
            @finish="mobileSubmit"
          >
            <a-form-item required hasFeedback name="mobile">
              <a-input v-model:value="formMobile.mobile" size="large" placeholder="请输入手机号">
                <template #prefix
                  ><mobile-outlined type="mobile" :style="{ color: 'rgba(0,0,0,.25)' }"
                /></template>
              </a-input>
            </a-form-item>
            <a-form-item has-feedback name="captcha">
              <a-input
                v-model:value="formMobile.captcha"
                size="large"
                type="text"
                placeholder="验证码"
              >
                <template #prefix>
                  <mail-outlined type="mail" :style="{ color: 'rgba(0,0,0,.25)' }" />
                </template>
                <template #suffix>
                  <a-button
                    class="getCaptcha"
                    tabindex="-1"
                    :disabled="state.smsSendBtn"
                    @click.stop.prevent="getCaptcha"
                    >{{ (!state.smsSendBtn && '获取验证码') || state.time + ' s' }}</a-button
                  >
                </template>
              </a-input>
            </a-form-item>
            <div id="captcha2" style="width: 100%; max-height: 40px; margin-bottom: 22px"></div>
            <a-form-item>
              <a-button type="primary" html-type="submit" size="large" :loading="loading" block>
                登录
              </a-button>
            </a-form-item>
          </a-form>
        </a-tab-pane>
      </a-tabs>
      <div>
        <router-link class="register" :to="{ name: 'register' }">注册账户</router-link>
        <router-link :to="{ name: 'ForgotPassword' }" class="forge-password" style="float: right">
          忘记密码
        </router-link>
      </div>
      <a-divider v-if="setting.oauth_login == 1">第三方登录</a-divider>
      <div
        v-if="setting.oauth_login == 1"
        style="display: flex; align-items: center; align-content: center; justify-content: center"
      >
        <a
          v-if="setting.wechat_login == 1"
          style="margin: 0px 10px"
          title="使用微信帐号登录"
          @click="wechatLogin"
        >
          <WechatOutlined :style="{ fontSize: '26px', color: '#07c160' }" />
        </a>
        <a
          v-if="setting.ww_login == 1"
          style="margin: 0px 10px"
          title="使用企业微信帐号登录"
          @click="wwLogin"
        >
          <icon-font type="anticon-el_icon-wechat-qy" size="28" />
        </a>
      </div>
    </a-spin>
    <a-modal
      v-model:open="wechat_qrcode_visible"
      title="请扫描二维码登录"
      :footer="null"
      width="350px"
    >
      <div id="wechat_qrcode"></div>
    </a-modal>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs, ref, onMounted, nextTick } from 'vue'
import { message, Divider, Spin } from 'ant-design-vue'
import { IconFont } from '@/components/iconfont'
import {
  UserOutlined,
  LockOutlined,
  MobileOutlined,
  MailOutlined,
  WechatOutlined
} from '@ant-design/icons-vue'
import { useRoute, useRouter } from 'vue-router'
import { requestSuccess, requestFailed } from '@/utils/feedback'
import { getSmsCaptcha } from '@/api/system/user'
import { getLoginParam } from '@/api/common'
import {
  validatePhone,
  validatePassword,
  validateCaptcha,
  validateUserName
} from '@/utils/validate'
import { useStore } from '@/store'

import { SvgIcon } from '@/components/svg-icon'

export default defineComponent({
  name: 'Login',
  components: {
    IconFont,
    UserOutlined,
    LockOutlined,
    WechatOutlined,
    SvgIcon,
    MobileOutlined,
    MailOutlined,
    [Spin.name]: Spin,
    [Divider.name]: Divider
  },
  setup() {
    const state = reactive<any>({
      loading: false,
      wechat_qrcode_visible: false,
      spinning: false,
      loadTips: '登录中',
      activeKey: ref('tab1'),
      setting: {},
      wechatData: {
        code: '',
        type: ''
      },
      formPwd: {
        username: '',
        authenticate: '',
        token: '',
        password: ''
      },
      formMobile: {
        mobile: '',
        authenticate: '',
        token: '',
        captcha: ''
      },
      state: {
        smsSendBtn: false,
        time: 60
      }
    })

    const store = useStore()
    const router = useRouter()
    const route = useRoute()

    if (route.query?.state == 'wx_login' && route.query.code) {
      state.spinning = true
      state.loadTips = '微信登录中……'
      state.wechatData.code = route.query.code
      state.wechatData.type = 'wx_login'
      oauthLogin(state.wechatData)
    }
    if (route.query?.state == 'ww_login' && route.query.code) {
      state.spinning = true
      state.loadTips = '企业微信登录中……'
      state.wechatData.code = route.query.code
      state.wechatData.type = 'ww_login'
      oauthLogin(state.wechatData)
    }

    onMounted(() => {
      getSetting()
    })

    const initCaptcha = () => {
      var divId = '#captcha'
      if (state.activeKey != 'tab1') {
        divId = '#captcha2'
      }
      if (state.setting.captcha_app_id != undefined) {
        ;(window as any).showCaptcha(state.setting.captcha_app_id, divId).then(function (res) {
          if (state.activeKey == 'tab1') {
            state.formPwd.token = res
            handleSubmit()
          } else {
            state.formMobile.token = res
            getCaptcha()
          }
        })
      } else {
        if (state.activeKey == 'tab1') {
          state.formPwd.token = 'notoken'
          handleSubmit()
        } else {
          state.formMobile.token = 'notoken'
          getCaptcha()
        }
      }
    }

    const getSetting = () => {
      getLoginParam({})
        .then((res) => {
          state.setting = res
          setTimeout(function () {
            ;(window as any).captchaInit(res.captcha_app_id)
          }, 100)
        })
        .catch((err) => {
          console.log(err)
        })
    }

    function oauthLogin(data) {
      store
        .dispatch('user/login', data)
        .then((res) => {
          if (res.code == 200) {
            const toPath = decodeURIComponent(
              (route.query?.redirect || '/dashboard/Workplace') as string
            )
            requestSuccess(null, '登录成功')
            router.replace(toPath).then(() => {
              if (route.name == 'login') {
                router.replace('/')
              }
            })
          } else {
            requestFailed(res)
          }
        })
        .catch((err) => {
          requestFailed(err)
        })
        .finally(() => {
          state.spinning = false
          state.loading = false
          message.destroy()
        })
    }

    const pwdRules = {
      username: [
        {
          required: true,
          message: '请输入用户名',
          trigger: ['blur', 'change']
        },
        {
          validator: validateUserName,
          trigger: ['blur', 'change']
        }
      ],
      password: [
        {
          required: true,
          message: '请输入密码',
          trigger: ['blur', 'change']
        },
        {
          validator: validatePassword,
          trigger: ['blur', 'change']
        }
      ]
    }
    const mobileRules = {
      mobile: [
        {
          required: true,
          message: '请输入手机号',
          trigger: ['blur', 'change']
        },
        {
          validator: validatePhone,
          trigger: 'change'
        }
      ],
      captcha: [
        {
          required: true,
          message: '请输入验证码',
          trigger: ['blur', 'change']
        },
        {
          validator: validateCaptcha,
          trigger: ['blur', 'change']
        }
      ]
    }
    const wechatLogin = () => {
      state.wechat_qrcode_visible = true
      setTimeout(() => {
        new (window as any).WxLogin({
          self_redirect: false,
          id: 'wechat_qrcode',
          appid: state.setting.wechat_appid,
          scope: 'snsapi_login',
          redirect_uri: window.location.href,
          state: 'wx_login',
          style: '',
          href: ''
        })
      }, 300)
    }
    const wwLogin = () => {
      state.wechat_qrcode_visible = true
      setTimeout(() => {
        ;(window as any).WwLogin({
          id: 'wechat_qrcode',
          appid: state.setting.ww_appid,
          agentid: state.setting.ww_agentid,
          redirect_uri: window.location.href,
          state: 'ww_login',
          href: ''
        })
      }, 300)
    }

    function handleSubmit() {
      if (state.formPwd.token == '') {
        initCaptcha()
        return false
      }
      state.loading = true
      store
        .dispatch('user/login', state.formPwd)
        .then((res) => {
          if (res.code == 200) {
            const toPath = decodeURIComponent(
              (route.query?.redirect || '/dashboard/Workplace') as string
            )
            requestSuccess(null, '登录成功')
            router.replace(toPath).then(() => {
              if (route.name == 'login') {
                router.replace('/')
              }
            })
          } else {
            requestFailed(res)
          }
        })
        .catch((err) => {
          requestFailed(err)
        })
        .finally(() => {
          state.loading = false
          message.destroy()
          state.formMobile.authenticate = ''
          state.formMobile.token = ''
          state.formPwd.authenticate = ''
          state.formPwd.token = ''
        })
    }
    function mobileSubmit() {
      if (state.formMobile.token == '') {
        initCaptcha()
        return false
      }
      state.loading = true
      store
        .dispatch('user/login', state.formMobile)
        .then((res) => {
          if (res.code == 200) {
            const toPath = decodeURIComponent(
              (route.query?.redirect || '/dashboard/Workplace') as string
            )
            requestSuccess(null, '登录成功')
            router.replace(toPath).then(() => {
              if (route.name == 'login') {
                router.replace('/')
              }
            })
          } else {
            requestFailed(res)
          }
        })
        .catch((err) => {
          requestFailed(err)
        })
        .finally(() => {
          state.loading = false
          message.destroy()
        })
    }
    let interval = window.setInterval(() => {})
    function getCaptcha() {
      if (state.state.smsSendBtn == true) {
        return false
      }
      if (!state.formMobile.mobile) {
        requestFailed(null, '请输入手机号')
        return false
      }
      if (state.formMobile.token == '') {
        initCaptcha()
        return false
      }
      state.state.smsSendBtn = true
      interval = window.setInterval(() => {
        if (state.state.time-- <= 0) {
          state.state.time = 60
          state.state.smsSendBtn = false
          window.clearInterval(interval)
        }
      }, 1000)
      let hide = message.loading('验证码发送中..', 0)
      getSmsCaptcha({
        phone: state.formMobile.mobile,
        authenticate: state.formMobile.authenticate,
        token: state.formMobile.token,
        type: 'login'
      })
        .then((res) => {
          setTimeout(hide, 1000)
          if (res.code === 200) {
            requestSuccess(null, '验证码获取成功')
          } else {
            setTimeout(hide, 1)
            clearInterval(interval)
            state.state.time = 60
            state.state.smsSendBtn = false
            requestFailed(res)
          }
        })
        .catch((err) => {
          console.log(err)
          setTimeout(hide, 1)
          clearInterval(interval)
          state.state.time = 60
          state.state.smsSendBtn = false
          requestFailed(err)
        })
        .finally(() => {
          state.formMobile.authenticate = ''
          state.formMobile.token = ''
          state.formPwd.authenticate = ''
          state.formPwd.token = ''
        })
    }
    return {
      ...toRefs(state),
      handleSubmit,
      interval,
      oauthLogin,
      mobileSubmit,
      mobileRules,
      pwdRules,
      wechatLogin,
      wwLogin,
      getCaptcha
    }
  }
})
</script>

<style lang="scss" scoped>
::v-deep(.ant-tabs-nav) {
  width: 100% !important;

  .ant-tabs-tab {
    width: 45% !important;
    text-align: center;
  }
}
</style>
